<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="SpuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌" label-width="100px">
      <el-select v-model="SpuInfo.tmId" placeholder="请选择品牌">
        <el-option
          v-for="(tm, index) in TrademarkList"
          :value="tm.id"
          :label="tm.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="SpuInfo.description"
        type="textarea"
        rows="4"
        placeholder="SPU描述"
      ></el-input>
    </el-form-item>

    <el-form-item label="SPU图片">
      <el-upload
        action="/dev-api/admin/product/fileUpload"
        list-type="picture-card"
        :file-list="SpuImageList"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select
        v-model="saleAttrIdName"
        :placeholder="
          unSelectedSaleAttrList.length
            ? `还有${unSelectedSaleAttrList.length}未选择`
            : '没有啦！！！'
        "
      >
        <el-option
          :label="unSelectedSaleAttr.name"
          :value="`${unSelectedSaleAttr.id}:${unSelectedSaleAttr.name}`"
          v-for="(unSelectedSaleAttr, index) in unSelectedSaleAttrList"
          :key="unSelectedSaleAttr.id"
        ></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus" @click="addArr"
        >添加销售属性</el-button
      >
      <el-table border style="width: 100%" :data="SpuInfo.spuSaleAttrList">
        <el-table-column type="index" align="center" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="saleAttrName" label="属性名" width="150">
        </el-table-column>
        <el-table-column prop="prop" label="属性值名称列表" width="width">
          <template v-slot="{ row, $index }">
            <el-tag
              style="margin: 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              closable
              :disable-transitions="false"
              v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              >{{ saleAttrValue.saleAttrValueName }}</el-tag
            >

            <el-input
              v-model="row.saleAttrValueName"
              v-if="row.isEdit"
              class="input-new-tag"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >添加</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="150">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delet($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="back">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      saleAttrIdName: "", //收集选择要添加的销售属性信息的名称和id id:name
      SpuInfo: {
        category3Id: "",
        description: "", //输入的描述
        spuName: "", //输入的spu名称
        tmId: "", //选择的品牌id
        spuImageList: [], //图片列表
        spuSaleAttrList: [], //销售属性列表
      }, //当前选中spu详细信息
      SpuImageList: [], //收集图片

      TrademarkList: [], //所有品牌信息
      BaseSaleAttrList: [], //所有销售属性信息
      dialogImageUrl: "",
      dialogVisible: false,
      category3Id: "",
    };
  },
  methods: {
    /* 点击取消 返回初始页 */
    back() {
      this.$emit("update:visible", false);
      Object.assign(this._data, this.$options.data());
    },
    /* 从添加属性进入  初始化请求数据 */
    async fromAdd(idList) {
      this.category3Id = idList.category3Id;
      /* console.log("add") */
      // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      try {
        const re1 = await this.$api.trademark.getTrademarkList();
        if (re1.code === 20000 || re1.code === 200) {
          /* console.log(re1.data) */
          this.TrademarkList = re1.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }

      try {
        const re2 = await this.$api.spu.getBaseSaleAttrList();
        if (re2.code === 20000 || re2.code === 200) {
          /* console.log(re2.data) */
          this.BaseSaleAttrList = re2.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }
    },
    /* 从修改属性进入  初始化请求数据 */
    async fromSet(spuId, idList) {
      this.category3Id = idList.category3Id;

      /* console.log("set") */
      // http://localhost:9529/dev-api/admin/product/getSpuById/6506
      // http://localhost:9529/dev-api/admin/product/spuImageList/6506
      // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      try {
        const re1 = await this.$api.trademark.getTrademarkList();
        if (re1.code === 20000 || re1.code === 200) {
          /* console.log(re1.data) */
          this.TrademarkList = re1.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }

      try {
        const re2 = await this.$api.spu.getBaseSaleAttrList();
        if (re2.code === 20000 || re2.code === 200) {
          /* console.log(re2.data); */
          this.BaseSaleAttrList = re2.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }

      try {
        const re3 = await this.$api.spu.GetSpuInfo(spuId);
        if (re3.code === 20000 || re3.code === 200) {
          /* console.log(re3.data.spuSaleAttrList); */
          this.SpuInfo = re3.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }
      try {
        const re4 = await this.$api.sku.getSpuImageList(spuId);
        if (re4.code === 20000 || re4.code === 200) {
          /* console.log(re4.data) */
          re4.data.forEach((item) => {
            item.url = item.imgUrl;
            item.name = item.imgName;
          });
          this.SpuImageList = re4.data;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        this.$message.error("请求获取数据失败");
      }
    },
    /* 删除图片 */
    handleRemove(file, fileList) {
      this.SpuImageList = fileList;
    },
    /* 浏览图片 */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /* 添加图片 */
    handleSuccess(res, file, fileList) {
      this.SpuImageList = fileList;
    },
    /* 添加销售属性 */
    addArr() {
      // 获取收集的id和name
      /* console.log(this.saleAttrIdName); */
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(":");
      // 构造成一个销售属性对象
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      /* console.log(obj)
        return */
      // 添加到指定的位置
      this.SpuInfo.spuSaleAttrList.push(obj);
      // 清空选中的信息
      this.saleAttrIdName = "";
    },
    //点击添加销售属性值
    showInput(row) {
      this.$set(row, "isEdit", true);
      this.$set(row, "saleAttrValueName", "");
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    //删除属性值
    delet($index) {
      this.SpuInfo.spuSaleAttrList.splice($index, 1);
    },
    //失去焦点 或者回车
    handleInputConfirm(row) {
      /* 判断是否为空 */
      /* console.log(row); */
      let { saleAttrValueName, baseSaleAttrId } = row;
      if (saleAttrValueName.trim() === "") {
        row.saleAttrValueName = "";
        row.isEdit = false;
        return;
      }

      /* 判断是否有重复的属性值名吃 */
      let isRepetition = row.spuSaleAttrValueList.some((item) => {
        item.saleAttrValueName === saleAttrValueName;
      });
      if (isRepetition) {
        this.$message.error("输入的属性值名称不能重复！！！");
        row.saleAttrValueName = "";
        row.isEdit = false;
        return;
      }
      /* 满足条件后  把数据收集到对象中 插入列表 */
      let obj = { saleAttrValueName, baseSaleAttrId };
      row.spuSaleAttrValueList.push(obj);
      row.saleAttrValueName = "";
      row.isEdit = false;
    },
    //保存
    async save() {
      /* console.log("this", this); */
      let { SpuInfo, category3Id, SpuImageList } = this;
      SpuInfo.category3Id = category3Id;
      SpuInfo.spuImageList = SpuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data,
        };
      });
      /* console.log( SpuInfo.spuImageList) */
      SpuInfo.spuSaleAttrList.forEach((item) => {
        delete item.isEdit;
        delete item.saleAttrValueName;
      });
      /* console.log(SpuInfo); */

      try {
        const re = await this.$api.spu.saveSpuInfo(SpuInfo);
        if (re.code === 20000 || re.code === 200) {
          this.$message.success("保存spu成功");
          this.$emit("update:visible", false);
          /* 清空数据 */
          this.$emit("backSuccess", SpuInfo.id);
          Object.assign(this._data, this.$options.data());
        } else {
          this.$message.error("error");
        }
      } catch (error) {
        this.$message.error("请求error");
      }
    },
  },
  computed: {
    /* 计算未选择的属性值列表 */
    unSelectedSaleAttrList() {
      return this.BaseSaleAttrList.filter((item) => {
        return this.SpuInfo.spuSaleAttrList.every((item1) => {
          return item1.saleAttrName !== item.name;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>